package com.acerola.mrpc;

import com.acerola.mrpc.handler.RpcServerHandler;
import com.acerola.mrpc.protocol.MessageCodecSharable;
import com.acerola.mrpc.protocol.MessageDecode;
import com.acerola.mrpc.protocol.MessageEncode;
import com.acerola.mrpc.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: mrpc
 * @description: rpc服务端
 * @author: Acerola
 * @create: 2022-12-10 18:43
 **/
@Slf4j
public class Server {
    private String serverAddress;
    private int serverPort;

    public Server(String serverAddress, int serverPort) {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
    }

    public void startRpcServer() {
        log.debug("begin start Netty server");
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable messageCodec = new MessageCodecSharable();
        RpcServerHandler rpcServerHandler = new RpcServerHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(loggingHandler);
//                    ch.pipeline().addLast(messageCodec);
                    ch.pipeline().addLast(new MessageDecode());
                    ch.pipeline().addLast(new MessageEncode());
                    //handler
                    ch.pipeline().addLast(rpcServerHandler);
                }
            });
            Channel channel = serverBootstrap.bind(this.serverAddress, this.serverPort).sync().channel();
            log.debug("Server started Success on Port:" + this.serverPort);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
